/**
 * @author [siwi]
 * @email [siwi@siwi.me]
 * @create date 2017-11-11 09:25:38
 * @modify date 2017-11-11 09:25:38
 * @desc [description]
*/
const BootApi = require('../api/BootApi')
const Util = require('../lib/Util')
const Redis = require('../lib/redis').connect
class BootApiController {
    constructor() {

    }
    /**
     * api 网关
     * @param {*} ctx 
     * @param {*} next 
     */
    async gateway (ctx, next) {
        let require = ['method'];
        let data = ctx.request.body
        let ip = ctx.request.ip
        if (data['siwi_debug']) {
            data['ctx'] = ctx
            data['next'] = next
        }
        
        /** 参数检查 **/
        let check = await Util.check_require(require, data)
        if (check) {
            ctx.throw(200, `缺少必要参数：${check}`)
        }
        /** IP 黑名单 接口频率限制 **/
        let ip_in_blacklist = await Redis.hget('CACHE_BLACKLIST_SIWI', ip)
        
        if (ip_in_blacklist) {
            ctx.throw(200, `请求出错 黑名单限制`)
        }
        /** IP 访问频率限制 **/
        let times = await Redis.hget('CACHE_SIWI_IP_API_TIMES', ip)

        if (times > 10000) {
            ctx.throw(200, `请求次数限制`)
        }

        /** 接口统计 **/
        let event_data = {
            methods: ctx.request.body.method,
            id: ctx.request.ip,
            create_at: Date.now()
        }
        await Redis.lpush('CACHE_SIWI_API_EVENT', JSON.stringify(event_data))

        
        /** 计算ip统计次数 **/ 
        await Redis.hincrby('CACHE_SIWI_IP_API_TIMES', ip, 1)
        await Redis.expire('CACHE_SIWI_IP_API_REQUEST_TIMES', 60)
        // 处理逻辑
        let res = await BootApi.gateway(data)
        console.log(res)
        if (res['ret'] == -1) {
            ctx.throw(200, res['msg'])
        }
        ctx.body = res
        
    }
    
}

module.exports = new BootApiController()